package com.ruoyi.vim.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.api.vo.ImServiceVO;
import com.ruoyi.api.vo.ServiceDetailVO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.vim.mapper.ImServiceMapper;
import com.ruoyi.vim.domain.ImService;
import com.ruoyi.vim.service.IImServiceService;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客服Service业务层处理
 *
 * @author wgp
 * @since 2022-12-11
 */
@Service
public class ImServiceServiceImpl extends ServiceImpl<ImServiceMapper, ImService> implements IImServiceService {
    @Autowired
    private ImServiceMapper imServiceMapper;

    @Override
    public boolean add(ImServiceVO vo) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        List<Long> userIds = vo.getUserIds();
        if(!CollectionUtils.isEmpty(userIds)) {
            List<ImService> list = new ArrayList<>();
            Date date = new Date();
            userIds.stream().forEach(t -> {
                QueryWrapper<ImService> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", t);
                ImService one = this.getOne(queryWrapper);
                if (one == null) {
                    ImService imService = new ImService();
                    imService.setServiceType(vo.getServiceType());
                    imService.setStatus(vo.getStatus());
                    imService.setUserId(t);
                    imService.setCreateBy(String.valueOf(user.getUserId()));
                    imService.setCreateTime(date);
                    list.add(imService);
                }
            });
            return this.saveBatch(list);
        }

        return false;
    }

    @Override
    public boolean edit(ImService imService) {
        if (imService.getId() != null) {
            ImService service = this.getById(imService.getId());
            BeanUtils.copyProperties(imService, service);
            SysUser user = SecurityUtils.getLoginUser().getUser();
            service.setUpdateBy(String.valueOf(user.getUserId()));
            service.setUpdateTime(new Date());
            return this.updateById(service);
        }
        return false;
    }

    @Override
    public ServiceDetailVO getServiceDetailInfo(Long userId) {
        return imServiceMapper.queryServiceByUserId(userId);
    }
}
